package com.bkhc.common.util;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.bkhc.common.service.ApiInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class NoModleDataListener extends AnalysisEventListener<Map<Integer,String>> {
    private static final Logger LOGGER = LoggerFactory.getLogger(NoModleDataListener.class);
    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 500;
    List<List<String>> list = new ArrayList<List<String>>();
    @Override
    public void invoke(Map<Integer,String> data, AnalysisContext context) {
        LOGGER.info("解析到一条数据:{}", JSON.toJSONString(data));
        List<String> dataline = new ArrayList<>();
        for(int key:data.keySet()){
            dataline.add(data.get(key));
        }
        list.add(dataline);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        List<String> dataline = new ArrayList<>();
        for(int key:headMap.keySet()){
            dataline.add(headMap.get(key));
        }
        list.add(dataline);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        LOGGER.info("所有数据解析完成！");
    }
    /**
     * 加上存储数据库
     */
    private void saveData() {
        LOGGER.info("{}条数据，开始解析！", list.size());
        LOGGER.info("解析成功！");
    }

    public List<List<String>> getResult(){
        return list;
    }
}